import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  getUserInfo,
  LoginData,
} from '@/api/user';
import { 
  setToken, clearToken, 
  setUserOrganization,
  clearUserOrganization,
  getUserOrganization,
  setUserInfo as setStorageUserInfo,
  getUserInfo as getStorageUserInfo,
} from '@/utils/auth';

import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';
import { isUndefined, isNull } from 'lodash';


// 角色配置
const rolesObj = {
  'organization_personnel': 'user',
  'organization': 'admin'
}


const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: undefined,
    username: undefined,
    nickname: undefined,
    mobile: undefined,
    avatar: undefined,
    score: undefined,
    token: undefined,
    user_id: undefined,
    createtime: undefined,
    expiretime: undefined,
    expires_in: undefined,
    group_key: undefined,
    role: undefined,
    organization: undefined,
    risk_control_status: undefined
  }),

  getters: {
    userInfo(state: UserState): UserState {
      if(!isUndefined(state?.id) && !isNull(state?.id)){
        return { ...state };
      } else {
        return getStorageUserInfo();
      }
    },
    getUserRole(state: UserState) : string {
      if(!isUndefined(state?.id) && !isNull(state?.id)){
        return state?.role;
      } else {
        let userInfo = getStorageUserInfo()
        return userInfo?.role;
      }
    },
    getUserRiskControlStatus(state: UserState): number {
      if(!isUndefined(state?.organization) && !isNull(state?.organization)){
         return Number(state?.organization?.risk_control_status || 0)
      } else {
        const itemObj: any = getUserOrganization();
        return Number(itemObj?.risk_control_status || 0)
      }
    }
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },

    // 同步localStorage 数据到 state 对象中
    synchUserInfoFromStorage(){
      if(isUndefined(this.id) || isNull(this.id)){
        let userInfo = getStorageUserInfo();
        if(!isUndefined(userInfo) && !isNull(userInfo)){
          if(!isUndefined(userInfo?.id) && !isNull(userInfo?.id)){
              this.setInfo(userInfo);
          }
        }
      }
    },

    // 设置用户信息
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // 重置用户信息
    resetInfo() {
      this.$reset();
    },

    // 获取用户信息
    async info() {
      // const res = await getUserInfo();
      // this.setInfo(res.data);
    },

    // 用户登录
    async login(loginForm: LoginData) {
      try {
        const { data  }: any = await userLogin(loginForm);
          let storeUserInfo = {
            ...data?.userinfo,
            organization: data?.organization, 
            role: rolesObj[data?.userinfo?.group_key] || ''
          };
          this.setInfo(storeUserInfo);
          setToken(data?.userinfo?.token);
          setStorageUserInfo(storeUserInfo);
          setUserOrganization(JSON.stringify(data?.organization || {}))
      } catch (err) {
        clearToken();
        clearUserOrganization();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      clearUserOrganization();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
